import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { NotificationService, BullySubjectService, ToolsService } from 'app/shared/service';
import { Subject } from 'rxjs';
import { NzModalService } from 'ng-zorro-antd';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';
import { AddVMSService } from '../add-vms/add-vms.service';
import { DisseminationService } from '../../dissemination-management.service';
import { graphic } from 'echarts';
import { PublicService } from 'app/public/public.service';
import { DialogService } from 'app/shared/dialog';
import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: 'itmp-message-library-list',
    templateUrl: './message-library-list.component.html',
    styleUrls: ['./message-library-list.component.css']
})
export class MessageLibraryListComponent implements OnInit {
    search$ = new Subject<object>();
    @Output() openModal = new EventEmitter();
    @Output() setSelectData = new EventEmitter();
    pagination: any; // 分页数据的对象
    searchData: any; // 搜索数据的对象
    listOfData = null; // 列表数据的数组
    renderHeader = null; // 表头数据的数组
    toolbarList = [
        // 工具条栏
        // { className: 'icon-chakan' },
        // { className: 'icon-dingwei' },
        { className: 'icon-dayinfuyin-' }
        // { className: 'icon-screenfull' },
        // { className: 'icon-xiazai' }
    ];
    createButton = false;
    editButton = false;
    deleteButton = false;
    printButton = false;
    // access: Array<any>;
    // 筛选框下拉列表
    selectionList = {
        Category_Name: ['VMS', 'CCTV', 'VD', 'TSC']
    };
    selectMessageLibrary: any;
    selectEquipmentData = null;
    now = null;
    accessButton = {
        Create: false,
        Edit: false,
        Delete: false,
        PRINT: false
    };
    disabled = false;
    constructor(
        private msg: NotificationService,
        private modalService: NzModalService,
        private addService: AddVMSService,
        private diss: DisseminationService,
        private pub: PublicService,
        private dialog: DialogService,
        private translate: TranslateService,
        private tools: ToolsService
    ) {}

    ngOnInit() {
        this.searchPipeSet();
        this.renderHeader = [
            {
                name: 'ID',
                key: null,
                value: 'message_id',
                isChecked: true
            },
            {
                name: 'Category_Name',
                key: null,
                value: 'category_name',
                isChecked: true
            },
            {
                name: 'Template_Name',
                key: null,
                value: 'template_name',
                isChecked: true
            },
            {
                name: 'Message_Content',
                key: null,
                value: 'MessageContent',
                isChecked: true
            }
        ];
        this.getSelectionList();
        this.initData();
        this.getData();
        this.getButtonAccess();
    }
    getButtonAccess() {
        this.accessButton = this.pub.getButtonAccess('8', this.accessButton);
    }
    // 搜索(防抖)
    onSearch(name): void {
        this.search$.next({ name: this.searchData[name] });
    }
    // 防抖函数注册
    searchPipeSet() {
        this.search$.pipe(debounceTime(1000), distinctUntilChanged()).subscribe((kw: any) => {
            this.pagination.currentPage = 1;
            this.getData();
        });
    }
    // 获取数据
    getData() {
        this.now = new Date().getTime();
        for (const item in this.searchData) {
            if (this.searchData.hasOwnProperty(item)) {
                if (this.searchData[item] === '') {
                    this.searchData[item] = null;
                }
            }
        }
        const params = {
            condition: this.searchData,
            pageNum: this.pagination.currentPage,
            pageSize: this.pagination.pageSize
        };
        this.diss.getMessageLibraryList(params).subscribe(res => {
            const content = res.data;
            if (!content) {
                this.listOfData = [];
                return;
            }
            this.listOfData = content.content;

            this.pagination.currentSize = content.numberOfElements;
            this.pagination.totalEle = content.totolElements;
        });
    }
    // 获取下拉列表数据
    getSelectionList() {
        const params = {
            condition: {
                category_id: null,
                category_name: null
            },
            pageNum: 1,
            pageSize: 1000
        };
        this.selectionList.Category_Name = [];
        this.diss.getCategoryList(params).subscribe(res => {
            this.selectionList.Category_Name = res.data.content;
            this.addService.setSelectionList('messageCategory', this.selectionList.Category_Name);
        });
    }
    // 初始化分页和搜索
    initData() {
        this.pagination = {
            totalEle: 10,
            pageSize: 10,
            currentPage: 1,
            currentSize: 10
        };
        this.searchData = {
            category_id: null,
            category_name: null,
            message_id: null,
            template_id: null,
            template_name: null
        };
        this.listOfData = [];
    }
    // 分页控件改变事件
    onPageChange(e) {
        this.pagination.currentPage = e;
        this.getData();
    }
    onSizeChange(e) {
        this.pagination.pageSize = e;
        const total = this.pagination.totalEle;
        const curPage = this.pagination.currentPage;
        this.pagination.currentPage = Math.ceil(total / e) < curPage ? Math.ceil(total / e) : curPage;
        this.getData();
    }
    // 点击tr取值
    clickTR(i): void {
        this.listOfData.forEach((data, index) => {
            data.active = false;
            if (i === index) {
                // 点击每个tr给与样式active
                data.active = true;
                this.selectMessageLibrary = data;
            }
        });
    }
    // 刷新
    refresh(): void {
        this.cancelActive();
        this.initData();
        this.getData();
    }
    // 取消选中
    cancelActive(): void {
        this.selectMessageLibrary = null;
        this.listOfData.forEach((data, index) => {
            if (data.active) {
                data.active = false;
                return;
            }
        });
    }
    // 新增和编辑功能
    addOrEdit(flag) {
        this.addService.setShowPage(0);
        if (flag === 'add') {
            const templateId = '1'; // 默认id为1的模板
            const id = this.pagination.totalEle + 1;
            const displayMessage = {
                deviceInfo: {
                    height: 56,
                    width: 320
                },
                category: {
                    categoryId: null,
                    categoryName: null
                },
                msgDisplayId: id,
                msgId: id,
                templateId,
                templatePages: [
                    {
                        pageSeq: 1,
                        graphics: [],
                        texts: [],
                        templateGraphics: [],
                        templateTexts: []
                    }
                ]
            };
            this.addService.setDisplayMessage(displayMessage);
            this.openModal.emit('Add');
        } else {
            if (this.selectMessageLibrary) {
                this.setSelectData.emit(this.selectMessageLibrary);
                const { category, msgDisplayId, msgId, template } = this.selectMessageLibrary;
                const templatePages = [],
                    graphics = [[]],
                    texts = [[]];
                // graphics fill
                (this.selectMessageLibrary.graphics || []).forEach(g => {
                    const page = g.pageSeq - 1;
                    if (!graphics[page]) {
                        graphics[page] = [];
                    }
                    graphics[page].push({
                        messageId: g.messageId,
                        graphicSeq: g.graphicSeq,
                        vmsGraphic: g.vmsGraphic
                    });
                });
                // text fill
                (this.selectMessageLibrary.texts || []).forEach(t => {
                    const page = t.pageSeq - 1;
                    if (!texts[page]) {
                        texts[page] = [];
                    }
                    texts[page].push(this.tools.isClone(t));
                });
                // fill templatePages
                if (template.templatePages && template.templatePages.length) {
                    const tp = template.templatePages[0];
                    const templateGraphics = [];
                    const templateTexts = [];
                    (tp.templateGraphics || []).forEach(tg => {
                        const page = tg.pageSeq - 1;
                        if (!templateGraphics[page]) {
                            templateGraphics[page] = [];
                        }
                        templateGraphics[page].push(this.tools.isClone(tg));
                    });
                    (tp.templateTexts || []).forEach(tt => {
                        const page = tt.pageSeq - 1;
                        if (!templateTexts[page]) {
                            templateTexts[page] = [];
                        }
                        templateTexts[page].push(this.tools.isClone(tt));
                    });
                    const pages = Math.max(graphics.length, texts.length, templateGraphics.length, templateTexts.length);
                    for (let i = 0; i < pages; i++) {
                        const temp = {
                            pageSeq: i + 1,
                            graphics: graphics[i] || [],
                            texts: texts[i] || [],
                            // templateId: item.templateId,
                            templateGraphics: templateGraphics[i],
                            templateTexts: templateTexts[i]
                        };
                        templatePages.push(temp);
                    }
                }

                const displayMessage = {
                    deviceConfig: template.deviceConfig,
                    category,
                    msgDisplayId,
                    msgId,
                    templateId: template.templateId,
                    templatePages,
                    deviceInfo: {
                        width: template.deviceConfig.width,
                        height: template.deviceConfig.height
                    }
                };
                this.addService.setDisplayMessage(displayMessage);
                this.openModal.emit('Edit');
            } else {
                this.msg.notify({ type: 'warning', path: 'DisseminationManagement.MessageLibrary.select_notify' });
            }
        }
    }
    // 删除
    delete(): void {
        if (this.selectMessageLibrary) {
            const tempTranslate = [
                { title: 'DisseminationManagement.MessageLibrary.Delete_Message' },
                { title: 'DisseminationManagement.MessageLibrary.Delete_Content' },
                { title: 'DisseminationManagement.MessageLibrary.Delete_Save' },
                { title: 'DisseminationManagement.MessageLibrary.Delete_Cancel' }
            ];
            tempTranslate.forEach(item => {
                this.translate.get(item.title).subscribe((res: string) => {
                    item.title = res || '';
                });
            });
            this.modalService.confirm({
                nzTitle: '<i class="iconfont icon-delete" style="font-size:24px"></i>' + tempTranslate[0].title,
                nzContent: '<p style="font-size:24px">' + tempTranslate[1].title + '?</p>',
                nzOkText: tempTranslate[2].title,
                nzOnOk: () => {
                    this.diss.deleteMessageLibrary(this.selectMessageLibrary.msgId).subscribe(res => {
                        // 判断当前页是否有数据
                        if ((this.pagination.totalEle - 1) / this.pagination.pageSize === this.pagination.currentPage - 1) {
                            this.pagination.currentPage = 1;
                        }
                        this.selectMessageLibrary = null;
                        this.getData();
                    });
                },
                nzCancelText: tempTranslate[3].title,
                nzOnCancel: () => {}
            });
        } else {
            this.msg.notify({ type: 'warning', path: 'DisseminationManagement.MessageLibrary.delete_notify' });
            // 提示用户没有选中项目
        }
    }
}
